<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;

class CityTerritorialBoundaryModel extends BaseModel
{
    use HasFactory;

    protected $table = "city_territorial_boundary";

    const LEVEL_COUNTRY  = "country";
    const LEVEL_PROVINCE = "province";
    const LEVEL_CITY     = "city";
    const LEVEL_DISTRICT = "district";

    /**
     * @param string $pAdcode
     * @param string $level
     * @return array
     */
    public static function getData($pAdcode = '', $level = ''): array
    {
        if ($level == '') {
            $level = CityTerritorialBoundaryModel::LEVEL_PROVINCE;
        }
        return CityTerritorialBoundaryModel::query()
            ->when(
                $pAdcode == '' && $level == CityTerritorialBoundaryModel::LEVEL_PROVINCE, function ($query) {
                $query->where("level", CityTerritorialBoundaryModel::LEVEL_PROVINCE);//默认省
            })
            ->when(
                $pAdcode && $level == CityTerritorialBoundaryModel::LEVEL_CITY, function ($query) use ($pAdcode) {
                $query->where("level", CityTerritorialBoundaryModel::LEVEL_CITY);//查询城市
                $query->where('pAdcode', $pAdcode);
            })
            ->when(
                $pAdcode && $level == CityTerritorialBoundaryModel::LEVEL_DISTRICT, function ($query) use ($pAdcode) {
                $query->where("level", CityTerritorialBoundaryModel::LEVEL_DISTRICT);//查询区
                $query->where('pAdcode', $pAdcode);
            })
            ->select(['id', 'pAdcode', 'adcode', 'cityCode', 'name', 'boundary'])
            ->get()
            ->each(function (CityTerritorialBoundaryModel $territorialBoundaryModel) use ($level) {
                $boundary = $territorialBoundaryModel->boundary ? json_decode($territorialBoundaryModel->boundary, true) : [];
                return [
                    'id'       => $territorialBoundaryModel->id,
                    'pAdcode'  => $territorialBoundaryModel->pAdcode,
                    'adcode'   => $territorialBoundaryModel->adcode,
                    'cityCode' => $territorialBoundaryModel->cityCode,
                    'name'     => $territorialBoundaryModel->name,
                    'boundary' => $boundary,
                ];
            })
            ->toArray();
    }

    /**
     * 市到区
     * @return HasMany
     */
    public function cityTerritorialBoundaryRelByCity(): HasMany
    {
        return $this->hasMany(CityTerritorialBoundaryModel::class, 'pAdcode', 'adcode')->where('level', 'district');
    }
}
